package com.example.yiwei.crm.view.activity.healthActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.BaseActivity;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetVisit;
import com.example.yiwei.crm.entity.CoorSeacherVisitActivity;
import com.example.yiwei.crm.entity.dockingEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.entity.personnalEntity;
import com.example.yiwei.crm.entity.scheduleEntity;
import com.example.yiwei.crm.json.FindSpinnerJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.view.activity.coordinationActivity.CoordinationVisitActivitu;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class addVisitActivity extends BaseActivity{
    private EditText edit_theme,edit_visit_gift,edit_present_value,edit_additional;
    private Spinner spinner_priority,spinner_task_state,spinner_manager;
    private Button btn_show;
    private ImageView img_back,img_commit;
    private TextView txt_visit_time,txt_title;
    private TimePickerView mpv;
    private String visit_time;
    private  String result;

    private  String result1;
    List<String> YXJBList;
    List<String> ZTList;
    List<Map<String,String>> YXJBSpinnerList;
    List<Map<String,String>> ZTSpinnerList;
    private ArrayAdapter adapter,adapter1,adapter3;
    private String priority,task_state,manager_name;
    private int priority_id,task_state_id,manager_id;
    dockingEntity dockingEntity;
    scheduleEntity scheduleEntity;
    personnalEntity personnalEntity;
    private SharedPreferences sp;
    List<managerEntity> managerList;
    List<String> managerlist;
    int i1 =1;
    int i2 =1;
    int i3 = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_visit);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        img_back= (ImageView) findViewById(R.id.add_visit_img_back);
        img_commit= (ImageView) findViewById(R.id.add_visit_img_commit);
        spinner_manager = (Spinner) findViewById(R.id.add_visit_spinner_manger);
        btn_show= (Button) findViewById(R.id.add_visit_btn_show);
        txt_visit_time= (TextView) findViewById(R.id.add_visit_txt_visit_time);
        txt_title= (TextView) findViewById(R.id.add_visit_txt_title);
        spinner_priority= (Spinner) findViewById(R.id.add_visit_spinner_priority);
        spinner_task_state= (Spinner) findViewById(R.id.add_visit_spinner_task_state);
        edit_additional= (EditText) findViewById(R.id.add_visit_edit_addtional);
        edit_present_value= (EditText) findViewById(R.id.add_visit_edit_present_value);
        edit_visit_gift= (EditText) findViewById(R.id.add_visit_edit_visit_gift);
        edit_theme= (EditText) findViewById(R.id.add_visit_edit_theme);
        edit_present_value.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        if ("update".equals(getIntent().getStringExtra("tag"))){
            scheduleEntity = GetVisit.scheduleEntity;
        }
        //创建选择器
        mpv = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置时间范围
        final Calendar calendar = Calendar.getInstance();
        mpv.setRange(calendar.get(Calendar.YEAR) - 100, calendar.get(Calendar.YEAR) + 100);
        //插入时间
        mpv.setTime(new Date());

        //选择监听
        mpv.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                visit_time=getTime(date);
                txt_visit_time.setText(visit_time);
            }
        });
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mpv.show();
            }
        });
        if ("update".equals(getIntent().getStringExtra("tag"))){
            txt_title.setText("修改拜访信息");
        }
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
//                result= NetWorkUtils.getCount(baseClass.find_visit_spinner_url,null);
//                dockDao dockDao=new dockDaoImpl();
//                YXJBSpinnerList=dockDao.queryDockingSpinnerMessage(result,1);
//                ZTSpinnerList=dockDao.queryDockingSpinnerMessage(result,2);
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("admin",sp.getString("admin",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                managerDao manaDao=new managerDaoImpl();
                managerList=manaDao.queryAllManager(baseClass.query_manager_url,json);
                String result1 = NetWorkUtils.getCount(baseClass.find_YXJB_URL,json);
                String result2 = NetWorkUtils.getCount(baseClass.find_RUZT_URL,json);
                YXJBSpinnerList = FindSpinnerJson.getSpinnerMessage(result1);
                ZTSpinnerList = FindSpinnerJson.getSpinnerMessage(result2);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        managerlist = new ArrayList<String>();
                        YXJBList=new ArrayList<String>();
                        ZTList=new ArrayList<String>();
                        YXJBList.add(0,"");
                        for (int i = 0;i<managerList.size();i++){
                            managerlist.add(managerList.get(i).getManager_name());
                        }
                        adapter1 = new ArrayAdapter(addVisitActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner,managerlist);
                        adapter1.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        spinner_manager.setAdapter(adapter1);
                        spinner_manager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                if (position>0){
                                    manager_name = managerList.get(position-1).getManager_name();
                                    manager_id = managerList.get(position-1).getManager_id();
                                }
                                if ("updata".equals(getIntent().getStringExtra("tag"))&&i1==1){
                                    for (int i = 0;i<managerlist.size();i++){
                                        if (managerlist.get(i).equals(scheduleEntity.getManager_name())){
                                            spinner_manager.setSelection(i);
                                            Log.d("aa",scheduleEntity.getManager_name());
                                            i1++;
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        for (int i=0;i<YXJBSpinnerList.size();i++){
                            YXJBList.add(YXJBSpinnerList.get(i).get("AKJ03"));
                        }
                        adapter = new ArrayAdapter(addVisitActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, YXJBList);
                        adapter.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        spinner_priority.setAdapter(adapter);
                        spinner_priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                priority=spinner_priority.getSelectedItem().toString();
                                for (int i1=0;i1<YXJBSpinnerList.size();i1++){
                                    if (priority.equals(YXJBSpinnerList.get(i1).get("AKJ03"))){
                                        priority_id=Integer.valueOf(YXJBSpinnerList.get(i1).get("AKJ01"));
                                    }

                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                        if ("update".equals(getIntent().getStringExtra("tag"))&&i2==1){
                            scheduleEntity= GetVisit.get();
                            SpinnerAdapter spadapter1 = spinner_priority.getAdapter();
                            Integer i1 =scheduleEntity.getPriority_id();
                            if (i1!=null){
                                for (int i = 0;i<YXJBSpinnerList.size();i++){
                                    if (i1==Integer.valueOf(YXJBSpinnerList.get(i).get("AKJ01"))){
                                        priority= YXJBSpinnerList.get(i).get("AKJ03");
                                    }
                                }
                            }

                            if (priority!=null){
                                for (int i = 0;i<spadapter1.getCount();i++){
                                    if (priority.equals(spadapter1.getItem(i).toString())){
                                        spinner_priority.setSelection(i);
                                        i2++;
                                    }
                                }
                            }
                        }
                        ZTList.add(0,"");
                        for (int i=0;i<ZTSpinnerList.size();i++){
                            ZTList.add(ZTSpinnerList.get(i).get("AKK03"));
                        }
                        adapter3 = new ArrayAdapter(addVisitActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, ZTList);
                        adapter3.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        spinner_task_state.setAdapter(adapter3);
                        spinner_task_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                task_state=spinner_task_state.getSelectedItem().toString();
                                for (int i1=0;i1<ZTSpinnerList.size();i1++){
                                    if (task_state.equals(ZTSpinnerList.get(i1).get("AKK03"))){
                                        task_state_id=Integer.valueOf(ZTSpinnerList.get(i1).get("AKK01"));
                                    }
                                }

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                        if ("update".equals(getIntent().getStringExtra("tag"))&&i3==1){
                            SpinnerAdapter spadapter2 = spinner_task_state.getAdapter();
                            scheduleEntity= GetVisit.get();
                            Integer i2 =scheduleEntity.getTask_state_id();
                            if (i2!=null){
                                for (int i = 0;i<ZTSpinnerList.size();i++){
                                    if (i2==Integer.valueOf(ZTSpinnerList.get(i).get("AKK01"))){
                                        task_state= ZTSpinnerList.get(i).get("AKK03");
                                    }
                                }
                            }

                            if (task_state!=null){
                                for (int i = 0;i<spadapter2.getCount();i++){
                                    if (task_state.equals(spadapter2.getItem(i).toString())){
                                        spinner_task_state.setSelection(i);
                                        i3++;
                                    }
                                }
                            }
                        }

                    }
                });
            }
        }).start();
        if ("update".equals(getIntent().getStringExtra("tag"))){
            edit_theme.setText(scheduleEntity.getSchedule_theme());
            txt_visit_time.setText(scheduleEntity.getVisit_time());
            edit_visit_gift.setText(scheduleEntity.getVisit_gift());
            edit_present_value.setText(scheduleEntity.getGift_value());
            edit_additional.setText(scheduleEntity.getAdditional_remarks());

        }

        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("".equals(edit_theme.getText().toString())||edit_theme.getText().toString()==null){
                    Toast.makeText(addVisitActivity.this, "任务主题不能为空", Toast.LENGTH_SHORT).show();
                }else if ("".equals(txt_visit_time.getText().toString())||txt_visit_time.getText().toString()==null){
                    Toast.makeText(addVisitActivity.this, "请选择拜访时间", Toast.LENGTH_SHORT).show();
                }else {
                    add();
                }

            }
        });

    }
    public void add(){
        img_commit.setVisibility(View.GONE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object=sc.storage(sp);
                try {
                    object.put("KPA02",edit_theme.getText().toString());
                    if(manager_id==0){
                        object.put("KPA03",sp.getString("UAB01",null));
                        object.put("KPA11",sp.getString("UAB03",null));
                    }else {
                        object.put("KPA03",manager_id);
                        object.put("KPA11",manager_name);
                    }


                    object.put("AKJ01",priority_id);
                    object.put("AKK01",task_state_id);
                    object.put("CID03",sp.getString("CID03",null));
                    object.put("KPA06",txt_visit_time.getText().toString());
                    object.put("KPA09",edit_visit_gift.getText().toString());
                    if (edit_present_value.getText().toString()!=null&&!edit_present_value.getText().toString().equals("")){
                        object.put("KPA10",edit_present_value.getText().toString());
                    }
                    if ("update".equals(getIntent().getStringExtra("tag"))){
                        //协作人拜访修改
                        object.put("addoredit","edit");
                        object.put("KPA01",scheduleEntity.getVisit_id());
                    }else {
                        object.put("addoredit","add");
                    }
                    object.put("REK01",edit_additional.getText().toString());
                    object.put("KXA01",getIntent().getExtras().getInt("docking_id"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json=object.toString();
                if ("health".equals(getIntent().getStringExtra("TAG"))){
                    //对接人添加拜访接口
                    result1=NetWorkUtils.getCount(baseClass.add_visit_url,json);
                }
                    result1 = NetWorkUtils.getCount(baseClass.edit_BF_URL,json);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject object1=new JSONObject(result1);
                            boolean boolen=object1.getBoolean("ifsuccess");
                            if(boolen){
                                if ("update".equals(getIntent().getStringExtra("tag"))){
                                    finish();
                                }else {
                                    Intent intent = new Intent(addVisitActivity.this, CoordinationVisitActivitu.class);
                                    intent.putExtra("dockid",getIntent().getExtras().getInt("docking_id"));
                                    startActivity(intent);
                                    finish();
                                }

                            }else {
                                img_commit.setVisibility(View.VISIBLE);
                                Toast.makeText(addVisitActivity.this, "添加拜访失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
//                        finish();
                    }
                });

            }
        }).start();

    }
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);

    }
    public  int countStr(String str1, String str2) {
        int counter=0;
        if (str1.indexOf(str2) == -1) {
            return 0;
        } else if (str1.indexOf(str2) != -1) {
            counter++;
            countStr(str1.substring(str1.indexOf(str2) +
                    str2.length()), str2);
            return counter;
        }
        return 0;
    }

}
